var request = require("request");
var EventProxy = require('eventproxy');
var config = require('../../config.json');
var _ = require('lodash');var pre_url = config.store.store_private;


exports.getCurrent = function (req, res) {
    if (req.session.user) {
        res.format_json(req.session.user, 0);
    } else {
        res.format_json({}, 500, "无法获取当前登录用户信息");
    }
};

exports.getUsers = function (req, res) {
    var keywords = req.query.keywords;
    request(config.auth.uc_private + "/users/query?keywords=" + keywords + "&client_id=" + config.auth.client_id + "&client_secret=" + config.auth.client_secret, function (error, resp) {
        if (!error) {
            res.format_json(JSON.parse(resp.body).data, 0);
        }
    })

};
exports.getDepenList = function (req, response) {
    var ep = new EventProxy();
    var user_name = req.params.user_name;
    var depen_list = [];

    ep.fail(function (err) {
        response.format_json(null, 500, err);
    });
    request(pre_url + '/store/orders?state=0&user=' + user_name, function (error, res) {
        if (!error) {
            var order_list = JSON.parse(res.body);
            var array = order_list.data;
            if (!array || 0 == array.length) {
                return response.format_json([]);
            }

            var allowed_dependency = [
                "mk",
                "core_node",
                "core_java",
                "app_plugin"
            ];
            ep.after('good_item_found', array.length, function () {
                response.format_json(depen_list, 0);
            });

            array.map(function (goods) {
                request(pre_url + '/store/good/' + goods.goods, function (error, res) {
                    if (error) {
                        ep.throw(error);
                    }
                    var good_info = JSON.parse(res.body).data;
                    //TODO custom_data还需处理（productName 和 fileName） 或者在发布的时候处理
                    var goods_info = {
                        name: good_info.name,
                        goods_title: good_info.title,
                        goods_version: good_info.version,
                        introduction: good_info.introduction,
                        supplier: good_info.supplier,
                        type: good_info.type,
                        custom_data: good_info.custom_data,
                        status: 3
                    }
                    if (_.indexOf(allowed_dependency, goods_info.type) >= 0) {
                        depen_list.push(goods_info);
                    }
                    ep.emit('good_item_found');
                });

            });
        } else {
            return ep.throw(error);
        }
    });

}